package com.ecarx.camera.worker.camera.interior;

import static com.ecarx.camera.constant.Constants.PHOTO_EXTENSION;
import static com.ecarx.camera.constant.Constants.SIMPLE_DATE_FORMAT;
import static com.ecarx.camera.constant.Constants.VIDEO_EXTENSION;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.location.Location;
import android.net.Uri;
import android.os.CountDownTimer;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import com.ecarx.camera.constant.Constants;
import com.ecarx.camera.data.ThumbnailData;
import com.ecarx.camera.ui.camera.ICameraUI;
import com.ecarx.camera.utils.AppExecutors;
import com.ecarx.camera.utils.LogUtils;
import com.ecarx.camera.utils.StorageUtils;
import com.ecarx.camera.utils.Utils;
import com.ecarx.camera.worker.camera.CameraListener;
import com.ecarx.camera.worker.camera.ICameraViewWorker;
import com.ecarx.camera.worker.camera.timer.RecordingTimerHelper;
import com.ecarx.camera.worker.config.ConfigManager;
import com.ecarx.camera.worker.config.OnLocationChangedListener;
import com.ecarx.camera.worker.config.OnModeChangedListener;
import com.ecarx.camera.worker.config.OnVideoMutedChangedListener;
import com.ecarx.camera.worker.config.OnZoomRatioChangedListener;
import com.ecarx.camera.worker.event.RecordingTimerEvent;
import com.ecarx.camera.worker.location.XCLocationManager;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.CameraView;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.internal.ExifHelper;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.Locale;

/**
 * 内部摄像头功能实现类
 */
public class InteriorCameraViewWorker implements ICameraViewWorker, OnLocationChangedListener, OnZoomRatioChangedListener, OnModeChangedListener, OnVideoMutedChangedListener {

    private static final String TAG = "InteriorCameraViewWorker";

    /**
     * 查询最近缩略图的volume
     */
    private static final String INTERIOR_VOLUME = "external";

    private ICameraUI mCameraUI;
    private CameraView mCameraView;

    private final RecordingTimerHelper mRecordingTimerHelper = new RecordingTimerHelper(Constants.FacingType.INTERIOR);
    private final Observer<RecordingTimerEvent> mRecordingTimerEventObserver = new Observer<RecordingTimerEvent>() {
        @Override
        public void onChanged(RecordingTimerEvent recordingTimerEvent) {
            if (Constants.FacingType.INTERIOR == recordingTimerEvent.facingType) {
                if (mCameraUI != null) {
                    mCameraUI.setVideoRecordingTimeText(recordingTimerEvent.hours, recordingTimerEvent.minutes, recordingTimerEvent.seconds);
                }
            }
        }
    };

    private final CameraListener mCameraListener = new CameraListener() {
        @Override
        public void onZoomChanged(float newValue, @NonNull float[] bounds, @Nullable PointF[] fingers) {
            float zoomRatio;
            if (newValue <= 0f) {
                zoomRatio = Constants.MIN_ZOOM_RATIO;
            } else {
                zoomRatio = newValue * Constants.MAX_ZOOM_RATIO * (Constants.MAX_ZOOM_RATIO - Constants.MIN_ZOOM_RATIO) + Constants.MIN_ZOOM_RATIO;
                if (zoomRatio >= Constants.MAX_ZOOM_RATIO) {
                    zoomRatio = Constants.MAX_ZOOM_RATIO;
                }
            }
            ConfigManager.getInstance().setZoomRatio(zoomRatio);
        }

        @Override
        public void onPictureTaken(@NonNull PictureResult result) {
            if (result == null || result.getFacing() != Facing.FRONT) {
                return;
            }
            LogUtils.d(TAG, "onPictureTaken result_length:" + (result == null ? "null" : (result.getData() == null ? 0 : result.getData().length)));
            String fileName = "PIC_" + SIMPLE_DATE_FORMAT.format(System.currentTimeMillis()) + PHOTO_EXTENSION;
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Constants.RELATIVE_PATH);
            contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
            Uri uriInsert = Utils.getApp().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            try {
                OutputStream os = Utils.getApp().getContentResolver().openOutputStream(uriInsert);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                bos.write(result.getData());
                bos.close();
            } catch (Throwable throwable) {
                LogUtils.w(TAG, "onPictureTaken writeFile " + fileName, throwable);
            }

            if(result.getLocation()!=null){
                ExifHelper.setExifLocation(uriInsert, result.getLocation().getLatitude(), result.getLocation().getLongitude());
            }

            if (mCameraUI != null) {
                mCameraUI.updateOnPictureTaken(true);
            }
        }

        @Override
        public void onVideoRecordingStart() {
            if (mCameraView == null || mCameraView.getFacing() != Facing.FRONT) {
                return;
            }
            LogUtils.d(TAG, "onVideoRecordingStart");
            mRecordingTimerHelper.start();
            if (mCameraUI != null) {
                mCameraUI.updateOnVideoRecordingStarted();
            }
        }

        @Override
        public void onVideoTaken(@NonNull VideoResult result) {
            if (result == null || result.getFacing() != Facing.FRONT) {
                return;
            }
            LogUtils.d(TAG, "onVideoTaken, result-> " + getVideoResultStr(result));
            if (mCameraUI != null) {
                mCameraUI.updateOnVideoTaken(true);
            }
        }

        @Override
        public void onCameraOpened(@NonNull CameraOptions options) {
            super.onCameraOpened(options);
            LogUtils.d(TAG, "onCameraOpened, options-> " + getOptionStr(options));
            if (mCameraUI != null) {
                mCameraUI.updateByZoomSupported(options != null && options.isZoomSupported());
            }
            ConfigManager.getInstance().setLocation(XCLocationManager.get().getLastLocation());
        }

        /**
         * 打印CameraOptions的相关信息
         * @param options
         * @return
         */
        private String getOptionStr(CameraOptions options) {
            if (options == null) {
                return "null";
            }
            StringBuilder result = new StringBuilder();
            result.append("{ supportedFacing:").append(options.getSupportedFacing()).append(" ");
            result.append("zoom_supported:").append(options.isZoomSupported()).append(" ");
            result.append("supportedPictureSizes:").append(options.getSupportedPictureSizes()).append(" ");
            result.append("supportedVideoSizes:").append(options.getSupportedVideoSizes()).append(" ");
            result.append("supportedPictureAspectRatio:").append(options.getSupportedPictureAspectRatios()).append(" ");
            result.append("supportedVideoAspectRatio:").append(options.getSupportedVideoAspectRatios()).append(" ");
            result.append("}");
            return result.toString();
        }

        /**
         * 打印录像结果的相关信息
         * @param result
         * @return
         */
        private String getVideoResultStr(VideoResult result) {
            if (result == null) {
                return "null";
            }
            StringBuilder resultStr = new StringBuilder();
            resultStr.append("{ file:").append(result.getFile()).append(" ");
            resultStr.append("isSnapshot:").append(result.isSnapshot()).append(" ");
            resultStr.append("size:").append(result.getSize()).append(" ");
            resultStr.append("}");
            return resultStr.toString();
        }
    };

    private long mPhotoTimerCountDown;
    private CountDownTimer mTakePhotoCountDownTimer;
    private CountDownTimer mRecordVideoCountDownTimer;

    private ContentResolver mContentResolver;

    private ContentObserver mContentObserver = new ContentObserver(AppExecutors.get().mainHandler()) {
        @Override
        public void onChange(boolean selfChange, @Nullable Uri uri, int flags) {
            super.onChange(selfChange, uri, flags);
            LogUtils.d(TAG, "ContentObserver onChanged, uri:" + uri + ", selfChange:" + selfChange + ", flags:" + flags);
            if (mCameraUI != null) {
                LogUtils.d(TAG, "thumbnail-> interior ContentObserver onChanged");
                mCameraUI.updateLatestThumbnail();
            }
        }
    };

    @Override
    public void init() {
    }

    @Override
    public void bindUI(ICameraUI cameraUI) {
        mCameraUI = cameraUI;
        if (cameraUI != null) {
            LiveEventBus.get(RecordingTimerEvent.class).observe(cameraUI.getFragment(), mRecordingTimerEventObserver);
        }
        registerThumbnailContentObserver();
    }

    @Override
    public void doOnResume() {
        LogUtils.d(TAG, "doOnResume");
        onLocationChanged(ConfigManager.getInstance().getLocation());
        onZoomRatioChanged(ConfigManager.getInstance().getZoomRatio());
        onModeChanged(ConfigManager.getInstance().isModeVideo());
        onInteriorVideoMutedChanged(ConfigManager.getInstance().isInteriorVideoMuted());
        ConfigManager.getInstance().addOnLocationChangedListener(this);
        ConfigManager.getInstance().addOnZoomRatioChangedListener(this);
        ConfigManager.getInstance().addOnModeChangedListener(this);
        ConfigManager.getInstance().addOnVideoMutedChangedListener(this);

        if (mCameraUI != null) {
            mCameraUI.showCountDownLay(false);
            mCameraUI.showVideoRecordingIndicator(false);
            mCameraUI.setVideoRecordingButtonEnable(true);
            mCameraUI.showSwitchModeLay(true);
            mCameraUI.setPhotoTimerChecked(ConfigManager.getInstance().isUsePhotoTimerCountdown());
            mCameraUI.setVideoTimelapseChecked(ConfigManager.getInstance().isUseVideoTimelapseMode());
            mCameraUI.setVideoMutedChecked(ConfigManager.getInstance().isInteriorVideoMuted());
        }
        mRecordingTimerHelper.stop();
    }

    @Override
    public void doOnPause() {
        LogUtils.d(TAG, "doOnPause");
        ConfigManager.getInstance().removeOnLocationChangedListener(this);
        ConfigManager.getInstance().removeOnZoomRatioChangedListener(this);
        ConfigManager.getInstance().removeOnModeChangedListener(this);
        ConfigManager.getInstance().removeOnVideoMutedChangedListener(this);

        if (mTakePhotoCountDownTimer != null) {
            mTakePhotoCountDownTimer.cancel();
        }
        if (mRecordVideoCountDownTimer != null) {
            mRecordVideoCountDownTimer.cancel();
        }

        if (mCameraView != null) {
            if (mCameraView.isTakingVideo()) {
                LogUtils.d(TAG, "doOnPause, stopVideo when isTakingVideo");
                mCameraView.stopVideo();
            }
            if (mCameraUI != null) {
                mCameraUI.updateVideoRecordingButton(mCameraView.isTakingVideo());
            }
        }
    }

    @Override
    public void doOnDestroy() {
        LogUtils.d(TAG, "doOnDestroy");
        if (mCameraView != null) {
            mCameraView.removeCameraListener(mCameraListener);
        }
        unregisterThumbnailContentObserver();
    }

    @Override
    public void setCameraLocation(Location location) {
        LogUtils.d(TAG, "setCameraLocation, location:" + (location == null ? " null" : " not null"));
        if (mCameraView != null && location != null) {
            mCameraView.setLocation(location);
        }
    }

    @Override
    public void setCameraZoom(float zoomRatio) {
        ConfigManager.getInstance().setZoomRatio(zoomRatio);
    }

    @Override
    public void setVideoMode(boolean isVideoMode) {
        ConfigManager.getInstance().setModeVideo(isVideoMode);
    }

    @Override
    public void setUsePhotoTimerCountdown(boolean usePhotoTimerCountdown) {
        ConfigManager.getInstance().setUsePhotoTimerCountdown(usePhotoTimerCountdown);
    }

    @Override
    public void setUseVideoTimelapseMode(boolean useVideoTimelapseMode) {
        ConfigManager.getInstance().setUseVideoTimelapseMode(useVideoTimelapseMode);
    }

    @Override
    public boolean setCameraAudioMuted(boolean isMuted) {
        return ConfigManager.getInstance().setInteriorVideoMuted(isMuted);
    }

    @Override
    public void doCapture() {
        if (checkStorage()) {
            return;
        }
        boolean usePhotoTimerCountdown = ConfigManager.getInstance().isUsePhotoTimerCountdown();
        if (!usePhotoTimerCountdown) {
            doCapture(0L);
        } else {
            long photoTimerCountdown = ConfigManager.getInstance().getPhotoTimerCountdown();
            doCapture(photoTimerCountdown);
        }
    }

    private void doCapture(long photoTimerCountdown) {
        if (photoTimerCountdown == 0L) {
            takePhotoInner();
        } else {
            if (mTakePhotoCountDownTimer != null) {
                mTakePhotoCountDownTimer.cancel();
            }
            if (mTakePhotoCountDownTimer == null || this.mPhotoTimerCountDown != photoTimerCountdown) {
                this.mPhotoTimerCountDown = photoTimerCountdown;
                mTakePhotoCountDownTimer = new CountDownTimer(photoTimerCountdown * 1000L + 999L, 1000L) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        long secondsUntilFinished = millisUntilFinished / 1000L;
                        if (secondsUntilFinished == photoTimerCountdown) {
                            if (mCameraUI != null) {
                                mCameraUI.showZoomButton(true);
                                mCameraUI.showSwitchModeLay(false);
                                mCameraUI.showCountDownLay(true);
                            }
                        }
                        if (mCameraUI != null) {
                            mCameraUI.setCountDownText(String.valueOf(secondsUntilFinished));
                        }
                        if (secondsUntilFinished == 1L) {
                            cancel();
                            AppExecutors.get().mainHandler().postDelayed(this::onFinish, 1000L);
                        }
                    }

                    @Override
                    public void onFinish() {
                        takePhotoInner();
                    }
                };
            }
            mTakePhotoCountDownTimer.start();
        }
    }

    private void takePhotoInner() {
        if (mCameraUI != null) {
            mCameraUI.updateOnPhotoTakingStarted();
        }
        if (mCameraView != null) {
            mCameraView.takePictureSnapshot();
        }
    }

    @Override
    public void startRecordVideo() {
        if (checkStorage()) {
            mCameraUI.updateOnVideoTaken(false);
            return;
        }
        recordVideo(ConfigManager.getInstance().isUseVideoTimelapseMode());
    }

    private void recordVideo(boolean videoTimelapseMode) {
        if (!videoTimelapseMode) {
            recordVideoInner();
        } else {
            if (mRecordVideoCountDownTimer == null) {
                long videoTimerCountdown = ConfigManager.getInstance().getPhotoTimerCountdown();
                mRecordVideoCountDownTimer = new CountDownTimer(videoTimerCountdown * 1000L + 999L, 1000L) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        LogUtils.d(TAG, "onTick, millisUntilFinished = [" + millisUntilFinished + "]");
                        long secondsUntilFinished = millisUntilFinished / 1000L;
                        if (secondsUntilFinished == videoTimerCountdown) {
                            if (mCameraUI != null) {
                                mCameraUI.showZoomButton(true);
                                mCameraUI.showSwitchModeLay(false);
                                mCameraUI.showCountDownLay(true);
                            }
                        }
                        if (mCameraUI != null) {
                            mCameraUI.setCountDownText(String.valueOf(secondsUntilFinished));
                        }
                        if (secondsUntilFinished == 1L) {
                            cancel();
                            AppExecutors.get().mainHandler().postDelayed(this::onFinish, 1000L);
                        }
                    }

                    @Override
                    public void onFinish() {
                        recordVideoInner();
                    }
                };
            } else {
                mRecordVideoCountDownTimer.cancel();
            }
            mRecordVideoCountDownTimer.start();
        }
    }

    private void recordVideoInner() {
        if (mCameraUI != null) {
            mCameraUI.showCountDownLay(false);
        }

        String fileName = "VID_" + SIMPLE_DATE_FORMAT.format(System.currentTimeMillis()) + VIDEO_EXTENSION;
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Video.Media.RELATIVE_PATH, Constants.RELATIVE_PATH);
        contentValues.put(MediaStore.Video.Media.DISPLAY_NAME, fileName);
        Uri uriInsert = Utils.getApp().getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
        try {
            OutputStream os = Utils.getApp().getContentResolver().openOutputStream(uriInsert);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            // bos.write();
            bos.close();
        } catch (Throwable throwable) {
            LogUtils.w(TAG, "recordVideoInner createFile " + fileName, throwable);
        }

        Cursor query = Utils.getApp().getContentResolver().query(uriInsert, null, null, null, null);
        if (query != null) {
            if (query.moveToFirst()) {
                int columnIndexOfAbsolutePath = query.getColumnIndex(MediaStore.Video.VideoColumns.DATA);
                if (columnIndexOfAbsolutePath > 0) {
                    String absolutePath = query.getString(columnIndexOfAbsolutePath);
                    if (mCameraView != null) {
                        mCameraView.takeVideoSnapshot(new File(absolutePath));
                    }
                }
            }
            query.close();
        }
    }

    @Override
    public void stopRecordVideo() {
        if (mCameraView != null && mCameraView.isTakingVideo()) {
            mCameraView.stopVideo();
            // 点击停止录像时停止计时
            LogUtils.d(TAG, "stopRecordVideo, stop timer.");
            mRecordingTimerHelper.stop();
        }
    }

    @Override
    public ThumbnailData getLatestThumbnail() {
        LogUtils.d(TAG, "getLatestThumbnail start");
        ThumbnailData thumbnailData = new ThumbnailData().setFacingType(Constants.FacingType.INTERIOR);
        Uri queryUri = MediaStore.Files.getContentUri(INTERIOR_VOLUME);
        String selection = MediaStore.MediaColumns.RELATIVE_PATH + " = ? AND " + MediaStore.MediaColumns.OWNER_PACKAGE_NAME + " = ?";
        String[] selectionArgs = new String[]{Constants.RELATIVE_PATH, Utils.getApp().getPackageName()};
        Cursor query = Utils.getApp().getContentResolver().query(queryUri, null, selection, selectionArgs, null);
        if (query != null) {
            LogUtils.d(TAG, "getLatestThumbnail query_count:" + query.getCount());
            if (query.moveToLast()) {
                do {
                    int id = Constants.INVALID_GALLERY_ID;
                    Bitmap bitmap = null;
                    int columnIndexOfId = query.getColumnIndex(MediaStore.Files.FileColumns._ID);
                    int columnIndexOfMediaType = query.getColumnIndex(MediaStore.Files.FileColumns.MEDIA_TYPE);
                    int columnIndexOfTrashed = query.getColumnIndex(MediaStore.MediaColumns.IS_TRASHED);
                    if (columnIndexOfId > 0 && columnIndexOfMediaType > 0 && columnIndexOfTrashed > 0) {
                        id = query.getInt(columnIndexOfId);
                        int mediaType = query.getInt(columnIndexOfMediaType);
                        int trashed = query.getInt(columnIndexOfTrashed);
                        if (trashed != Constants.GALLERY_NOT_TRASHED_VALUE) {
                            // 剔除已经标记为trashed的数据
                            continue;
                        }
                        if (mediaType == MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE) {
                            bitmap = MediaStore.Images.Thumbnails.getThumbnail(Utils.getApp().getContentResolver(), id, MediaStore.Images.Thumbnails.MINI_KIND, null);
                            thumbnailData.setVideo(false);
                        } else if (mediaType == MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO) {
                            bitmap = MediaStore.Video.Thumbnails.getThumbnail(Utils.getApp().getContentResolver(), id, MediaStore.Video.Thumbnails.MINI_KIND, null);
                            thumbnailData.setVideo(true);
                        }
                    }
                    if (bitmap != null) {
                        thumbnailData.setGalleryId(id);
                        thumbnailData.setBitmap(bitmap);
                        break;
                    }
                } while (query.moveToPrevious());
            }
            query.close();
            LogUtils.d(TAG, "getLatestThumbnail complete");
        }
        return thumbnailData;
    }

    @Override
    public void onLocationChanged(@Nullable Location location) {
        setCameraLocation(location);
    }

    @Override
    public void onZoomRatioChanged(float zoomRatio) {
        if (mCameraView != null) {
            float zoom;
            if (zoomRatio <= Constants.MIN_ZOOM_RATIO) {
                zoom = 0f;
            } else {
                zoom = (zoomRatio - Constants.MIN_ZOOM_RATIO) / (Constants.MAX_ZOOM_RATIO - Constants.MIN_ZOOM_RATIO);
            }
            LogUtils.d(TAG, "set zoom ------> onZoomRatioChanged zoomRatio:" + zoomRatio + ", zoom:" + zoom);
            mCameraView.setZoom(zoom);
        }
        if (mCameraUI == null) {
            return;
        }
        zoomRatio = Float.parseFloat(String.format(Locale.ENGLISH, "%.1f", zoomRatio));
        if (String.valueOf(Constants.MIN_ZOOM_RATIO).equals(String.valueOf(zoomRatio))) {
            mCameraUI.setZoomButtonChecked(false);
        } else {
            mCameraUI.setZoomButtonChecked(true);
        }
        mCameraUI.setZoomButtonText(zoomRatio);
    }

    @Override
    public void onModeChanged(boolean isModeVideo) {
        if (mCameraUI == null) {
            return;
        }
        if (isModeVideo) {
            mCameraUI.updateWhenVideoModeChecked();
        } else {
            mCameraUI.updateWhenPhotoModeChecked();
        }
    }

    @Override
    public void onInteriorVideoMutedChanged(boolean videoMuted) {
        if (mCameraView != null) {
            mCameraView.setAudio(videoMuted ? Audio.OFF : Audio.ON);
        }
    }

    @Override
    public void onExteriorVideoMutedChanged(boolean videoMuted) {
    }

    @Override
    public void setCameraView(CameraView cameraView) {
        mCameraView = cameraView;

        if (mCameraView == null) {
            return;
        }
        mCameraView.setOnTouchListener(new View.OnTouchListener() {
            boolean isDown = false;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        isDown = true;
                        break;
                    case MotionEvent.ACTION_POINTER_DOWN:
                    case MotionEvent.ACTION_POINTER_UP:
                        isDown = false;
                        break;
                    case MotionEvent.ACTION_UP:
                        if (isDown) {
                            if (cameraView != null && !cameraView.isTakingVideo() && mCameraUI != null) {
                                mCameraUI.toggleSwitchModeLay();
                                return true;
                            }
                        }
                        isDown = false;
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
        mCameraView.addCameraListener(mCameraListener);

    }

    /**
     * 检测磁盘空间
     * @return
     */
    private boolean checkStorage() {
        return mCameraUI != null && mCameraUI.getFragment() != null && StorageUtils.checkStorage(mCameraUI.getFragment().getChildFragmentManager());
    }

    /**
     * 注册缩略图的数据库监听
     */
    private void registerThumbnailContentObserver() {
        if (mCameraUI == null) {
            LogUtils.w(TAG, "registerThumbnailContentObserver, but cameraUI is null");
            return;
        }
        Fragment fragment = mCameraUI.getFragment();
        if (fragment == null) {
            LogUtils.w(TAG, "registerThumbnailContentObserver, but fragment is null");
            return;
        }
        Context context = fragment.getContext();
        if (context == null) {
            LogUtils.w(TAG, "registerThumbnailContentObserver, but context is null");
            return;
        }
        mContentResolver = context.getContentResolver();
        if (mContentResolver != null) {
            mContentResolver.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, mContentObserver);
            mContentResolver.registerContentObserver(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, mContentObserver);
            LogUtils.d(TAG, "registerThumbnailContentObserver complete");
        }
    }

    /**
     * 取消注册缩略图的数据库监听
     */
    private void unregisterThumbnailContentObserver() {
        if (mContentResolver != null) {
            mContentResolver.unregisterContentObserver(mContentObserver);
            LogUtils.d(TAG, "unregisterThumbnailContentObserver complete");
        } else {
            LogUtils.w(TAG, "unregisterThumbnailContentObserver, but contentResolver is null");
        }
    }
}
